<script setup>
import { ref, reactive } from 'vue'
import MaterialCode from './code.vue'
import { listDept } from '@/api/system/dept'

const { proxy } = getCurrentInstance()
const props = defineProps({
  data: {
    type: Object,
    default: () => {}
  },
  db: {
    type: Boolean,
    default: false
  },
  examine: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: '新增'
  }
})

// 封装 方法 字典查询
const {
  quality_standard // 质量标准
} = proxy.useDict('quality_standard')

const emit = defineEmits(['cancel', 'submit'])

const ruleFormRef = ref(null)

const selection = ref([])
const deptOptions = ref([])

const TableData = ref([])

const materialShow = ref(false)
// 新增字段
const ruleForm = reactive({
  materialCategory: '', // 物料类别
  demandDept: '', // 需求部门
  remark: '', // 备注
  reviewComments: '', // 评审意见
  enclosureUrl: '', // 附件
  materialList: []
})

if (props.data && props.data?.id) {
  for (let key in props.data) {
    ruleForm[key] = props.data[key]
    ruleForm.demandDept = Number(ruleForm.demandDept)
  }
}

const rules = reactive({
  demandDept: [{ required: true, message: '请选择需求部门', trigger: 'change' }],
  reviewComments: [{ required: true, message: '请填写评审意见', trigger: 'burl' }]
})

//明细项
const preservation = val => {
  // ruleForm.materialList = []
  ruleForm.materialCategory = val.materialType
  // ruleForm.materialList = [...ruleForm.materialList, ...val.list]
  // ruleForm.materialList = val.list
  val.list.forEach(item => {
    ruleForm.materialList.push(item)
  })
  ruleForm.materialList.forEach(item => (item.unitDict = item.materialUnitDict))

  materialShow.value = false
}

// 删除
const remove = () => {
  if (selection.value.length > 0) {
    selection.value.forEach(item => {
      const Find = ruleForm.materialList.findIndex(itemy => item.materialId == itemy.materialId)
      ruleForm.materialList.splice(Find, 1)
    })
  } else {
    ruleForm.materialList.splice(ruleForm.materialList.length - 1, 1)
  }
}

// 提交
const submit = () => {
  return new Promise((resolve, reject) => {
    ruleFormRef.value.validate((valid, fields) => {
      if (!valid) {
        resolve(false)
        proxy.warningMsg('请填写完整')
        return
      }
      ruleForm.materialList = ruleForm.materialList.map(item => ({
        materialId: item.materialId,
        materialCode: item.materialCode,
        materialName: item.materialName,
        planWeight: item.planWeight,
        qualityStandard: item.qualityStandard,
        unit: item.materialUnit,
        demandTime: item.demandTime
      }))
      resolve(ruleForm)
    })
  })
}

// 改变时
const selectChange = val => {
  ruleForm.materialList = []
  ruleForm.materialCategory = val
}

// 列表选中
const handleSelectionChange = selection => {
  selection.value = selection
}

function handleAdd(row) {
  listDept().then(response => {
    deptOptions.value = proxy.handleTree(response.data, 'deptId')
  })
  if (row != undefined) {
    ruleForm.demandDept = ''
  }
}
handleAdd()
defineExpose({ submit })
</script>

<template>
  <div class="app-container">
    <el-form
      ref="ruleFormRef"
      class="demo-ruleForm"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
      label-position="right"
      status-icon
    >
      <div class="flex">
        <el-form-item label="采购需求单号" v-if="props.title != '新增'">
          <el-input
            clearable
            v-model="ruleForm.purchaseNum"
            placeholder="请输入采购需求单号"
            :disabled="props.title != '新增'"
          />
        </el-form-item>
        <el-form-item label="需求部门" prop="demandDept">
          <el-tree-select
            :disabled="props.db"
            v-model="ruleForm.demandDept"
            :data="deptOptions"
            :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
            value-key="deptId"
            placeholder="选择上级部门"
            check-strictly
          />
        </el-form-item>
        <!-- <el-form-item label="类别" prop="materialCategory">
          <el-select
            :disabled="props.title != '新增'"
            @change="selectChange"
            v-model="ruleForm.materialCategory"
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="(item, index) in [
                { label: '原料', value: '1' },
                { label: '辅料', value: '2' }
              ]"
              :key="index"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item> -->
      </div>
      <div class="rk">
        <el-form-item label="备注" prop="remark">
          <el-input
            clearable
            :disabled="props.db"
            v-model="ruleForm.remark"
            :rows="3"
            type="textarea"
            placeholder="请输入备注"
          />
        </el-form-item>
      </div>

      <el-form-item label="上传附件" prop="enclosureUrl">
        <ImageUpload v-model="ruleForm.enclosureUrl" v-if="!props.db" />
        <ImagePreview :src="ruleForm.enclosureUrl" v-else />
      </el-form-item>
      <div class="rk">
        <el-form-item label="评审意见" v-if="props.examine">
          <el-input
            clearable
            v-model="ruleForm.reviewComments"
            :rows="4"
            type="textarea"
            placeholder="请输入评审意见"
          />
        </el-form-item>
      </div>

      <div class="rk">
        <el-form-item label="关结原因" prop="closeReason" v-if="props.title == '查看' && ruleForm.closeReason">
          <div>
            <span>{{ ruleForm.closeBy || `后端为空 ==>${ruleForm.closeBy}` }}:&emsp;</span>
            <span>{{ ruleForm.closeReason }}</span>
          </div>
        </el-form-item>
      </div>
    </el-form>
    <div class="flex-items-center flex-between">
      <div class="title">明细项</div>
      <div class="flex-between" v-if="props.title == '新增'">
        <el-tooltip class="box-item" effect="dark" content="添加" placement="top-start">
          <el-icon @click="materialShow = true"><Plus /></el-icon>
        </el-tooltip>
        <div style="margin: 0 10px"></div>
        <el-tooltip class="box-item" effect="dark" content="勾选删除" placement="top-start">
          <el-icon @click="remove()"><Minus /></el-icon>
        </el-tooltip>
      </div>
    </div>
    <!-- 表格数据 -->
    <el-table
      v-loading="loading"
      stripe
      border
      :data="ruleForm.materialList"
      style="margin-top: 10px"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" fixed="left" />
      <el-table-column label="序号" width="70" type="index" />
      <el-table-column label="物料编码" prop="materialCode" width="auto" />
      <el-table-column label="物料名称" prop="materialName" width="auto" />
      <el-table-column label="单位" prop="unitDict" width="auto" />
      <el-table-column label="计划数量" width="200">
        <template #default="scope">
          <el-input
            :disabled="props.db"
            clearable
            type="number"
            oninput="if(value<=0)value=''"
            v-model="scope.row.planWeight"
            placeholder="请填写内容"
          />
        </template>
      </el-table-column>
      <el-table-column label="计划单价(元)" prop="plannedUnitPrice" width="auto" v-if="props.title == '查看'" />
      <el-table-column label="下达数量" prop="lowerWeight" width="auto" v-if="props.title == '查看'" />

      <el-table-column label="规格型号" width="200">
        <template #default="scope">
          <el-input :disabled="props.db" clearable v-model="scope.row.specType" placeholder="请填写规格型号" />
        </template>
      </el-table-column>
      <el-table-column label="需求时间" width="250">
        <template #default="scope">
          <el-date-picker
            clearable
            :disabled="props.db"
            v-model="scope.row.demandTime"
            type="datetime"
            format="YYYY/MM/DD hh:mm:ss"
            value-format="YYYY-MM-DD hh:mm:ss"
            placeholder="请选择时间"
          />
        </template>
      </el-table-column>
    </el-table>
    <Material
      :is-show="materialShow"
      :dict="[
        { label: '原料', value: '1' },
        { label: '辅料', value: '2' }
      ]"
      :bdb="false"
      @preservation="preservation"
      @cancel="materialShow = false"
    />
  </div>
</template>

<style lang="scss" scoped>
.btn {
  margin-top: 20px;
}

.rk ::v-deep .el-form-item {
  width: 100% !important;
}
</style>
